import React, { useEffect, useState, useRef } from 'react'
import Keyboard from './components/Keyboard'
import Controller from './components/Controller'
import axios from 'axios'
import type { ListRes, MusicItem } from './types'

const App: React.FC = () => {
  const [list, setList]  = useState<MusicItem[]>([])
  const [currentMusic, setCurrentMusic] = useState<MusicItem | null>(null)
  const audioRef = useRef<HTMLAudioElement>(null)
  const [power, setPower] = useState(true)
  const [bank, setBank] = useState(true)
  const [volume, setVolume] = useState(100)

  const changeMusic = (music: MusicItem) => {
    console.log(power)
    if (power) {
      setCurrentMusic(music)
      audioRef.current?.load()
    }
  }

  useEffect(() => {
    const getList = async () => {
      const res = await axios.get<ListRes>('http://zyxcl.xyz/exam_api/music/list')
      setList(res.data.value)
    }

    getList()
  }, [])

  useEffect(() => {
    setCurrentMusic(null)
  }, [bank])


  useEffect(() => {
    audioRef.current!.volume = volume / 100
    console.log(volume / 100)
  }, [volume])

  return (
    <div className="app">
      <Keyboard power={power} list={list} changeMusic={changeMusic} />
      <Controller
        title={currentMusic?.id || ''}
        power={power}
        onPowerChange={setPower}
        bank={bank}
        onBankChange={setBank}
        volume={volume}
        onVolumeChange={setVolume}
      />
      <audio ref={audioRef} src={bank ? currentMusic?.bankUrl : currentMusic?.url} autoPlay></audio>
    </div>
  )
}

export default App